﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web.Mvc;
using System.ComponentModel;
using EIIS.Infrastructure.Service.System.Authority;
using EIIS.Infrastructure.Model.System.Authority;
using EIIS.Presentation.Controllers.CommonSupport;
using EIIS.Presentation.Controllers.ViewModel;
using EIIS.Common;
using EIIS.Common.Jsons;
using EIIS.FrameWork.Attributes;

namespace EIIS.Presentation.Controllers.System.Authority
{
    [Description("用户管理")]
    public class HospUserController : BaseController
    {
        public IHospUserManager HospUserManager { get; set; }
        public IRoleManager RoleManager { get; set; }

        [Description("用户管理页面")]
        [ViewPage]
        public ActionResult Index()
        {
            return View();
        }

        [Description("修改密码")]
        [ViewPage(false)]
        public ActionResult ModifyPWD()
        {
            if (this.HttpContext.User.Identity.IsAuthenticated)
            {
                string strLoginName = this.HttpContext.User.Identity.Name;
                HospUser entity = HospUserManager.GetUserByName(strLoginName);
                this.ViewData["entity"] = entity;
            }
            return View();
        }        

        [Description("新增人员")]
        [Function(ButtonID = "btnAdd")]
        public ActionResult Add()
        {
            HospUser entity = new HospUser();
            this.ViewData["entity"] = entity;
            return View();
        }

        [Description("修改人员")]
        [Function(ButtonID = "btnUpdate")]
        public ActionResult Edit(string id)
        {
            HospUser entity = HospUserManager.Get(id);
            this.ViewData["entity"] = entity;
            return View();
        }

        [Description("删除人员")]
        [Function(ButtonID = "btnDelete")]
        public ActionResult Delete(IList<string> idList)
        {
            MessageInfo msg = new MessageInfo();
            msg.IsSuccess = true;
            msg.Message = "删除成功";
            HospUserManager.Delete(idList.Cast<object>().ToList());
            return Json(msg);
        }

        [Description("修改密码")]
        [HttpPost]
        public ActionResult DoModifyPWD(HospUser entity)
        {
            MessageInfo msg = new MessageInfo();
            if (string.IsNullOrEmpty(entity.Id))
            {
                msg.IsSuccess = false;
                msg.Message = "修改失败，获取账号信息失败";
                return Json(msg);
            }
            var model = HospUserManager.Get(entity.Id);
            model.Pwd = HospUser.GetPwdMD5(entity.Pwd);
            HospUserManager.Update(model);
            msg.IsSuccess = true;
            msg.Message = "保存成功";
            return Json(msg);
        }

        [Description("保存角色")]
        [HttpPost]
        public ActionResult Save(HospUser entity)
        {
            MessageInfo msg = new MessageInfo();
            string strRoleList = Request["Roles"];
            if (string.IsNullOrEmpty(entity.Id))//新增
            {
                if (HospUserManager.IsExistWithLoginName(entity.LoginName, "-1", ""))
                {
                    msg.IsSuccess = false;
                    msg.Message = "新增失败，已存在该登录帐号的记录";
                    return Json(msg);
                }
                if (HospUserManager.IsExistWithCode(entity.Code, "-1", ""))
                {
                    msg.IsSuccess = false;
                    msg.Message = "新增失败，已存在该工号的记录";
                    return Json(msg);
                }
                entity.Roles = new Iesi.Collections.Generic.HashedSet<Role>();
                entity.Departments = new Iesi.Collections.Generic.HashedSet<Department>();
                entity.FavoriteMenus = new Iesi.Collections.Generic.HashedSet<MenuNode>();
               
                if (!string.IsNullOrEmpty(strRoleList))
                {
                    string[] roleList = strRoleList.Split(',');
                    foreach (string roleId in roleList)
                    {
                        entity.Roles.Add(RoleManager.Load(roleId));
                    }
                }
                entity.Id = Guid.NewGuid().ToString();
                string strInitPassword = entity.Pwd;
                if (string.IsNullOrEmpty(strInitPassword)) strInitPassword = ConfigHelper.GetConfigString("InitPWD");
                entity.Pwd = HospUser.GetPwdMD5(strInitPassword);
                HospUserManager.Save(entity);
            }
            else
            {
                var model = HospUserManager.Get(entity.Id);
                if (HospUserManager.IsExistWithCode(entity.Code, entity.Id, ""))
                {
                    msg.IsSuccess = false;
                    msg.Message = "修改失败，已存在该工号的记录";
                    return Json(msg);
                }
                if (!string.IsNullOrEmpty(strRoleList))
                {
                    model.Roles.Clear();
                    string[] roleList = strRoleList.Split(',');
                    foreach (string roleId in roleList)
                    {
                        model.Roles.Add(RoleManager.Load(roleId));
                    }
                }
                model.Name = entity.Name;
                model.State = entity.State;
                model.Description = entity.Description;
                HospUserManager.Update(model);
            }
            msg.IsSuccess = true;
            msg.Message = "保存成功";
            return Json(msg, "text/html", JsonRequestBehavior.AllowGet);
        }

        [Description("获取用户信息列表")]
        public ActionResult LoadAll(int page, int rows, string order, string sort)
        {
            long total = 0;
            var query = HospUserManager.LoadAllWithPage(out total, page, rows, order, sort).Select(u =>
            {
                StringBuilder sb = new StringBuilder();
                foreach (Role tempRole in u.Roles)
                {
                    sb.AppendFormat(",{0}", tempRole.Id);
                }
                if (sb.ToString().Length > 0)
                {
                    sb.Remove(0, 1);
                }
                var obj = new
                {
                    u.Id,
                    u.Name,
                    u.Code,
                    u.LoginName,
                    u.Pwd,
                    u.State,
                    u.InputCode1,
                    u.InputCode2,
                    u.InputCode3,
                    u.CreateTime,
                    u.Description,
                    Roles = sb.ToString()
                };
                return obj;
            });
            return this.JsonFormat(new GridData { total = total, rows = query.ToList() });
        }

        [Description("返回人员状态")]
        public ActionResult GetUserState(string id)
        {
            var ilist = EnumDescription.ToList<PersonState>();
            List<combobox_data> list = ilist.ToList().ConvertAll<combobox_data>(d => { return new combobox_data() { id = d.Value.ToString(), text = d.Key, selected = (d.Value.ToString() == id ? true : false) }; });
            return Json(list);
        }

        [Description("返回角色列表")]
        public ActionResult GetRoleList(string id)
        {
            if (string.IsNullOrEmpty(id)) id = string.Empty;
            var query = RoleManager.LoadAll().OrderBy(r => r.CreateTime);
            List<combobox_data> list = query.ToList().ConvertAll<combobox_data>(c => { return new combobox_data() { id = c.Id, text = c.Name, selected = (id.IndexOf(c.Id) != -1 ? true : false) }; });
            return this.Json(list);
        }
    }
}
